package com.excelement.smartwaterbase.service;

import com.excelement.smartwaterbase.domain.Mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Collection;
import java.util.Date;

@Service
public class MailImpl implements MailService {


    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendSimpleMail(Mail mail) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject(mail.getObject());
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom(from);
        // message.setTo("10*****16@qq.com","12****32*qq.com");
        if (!CollectionUtils.isEmpty(mail.getCopy())) {
            // 设置邮件抄送人，可以有多个抄送人
            message.setCc(String.join(",", mail.getCopy()));
        }
        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        message.setTo(String.join(",", mail.getTo()));

        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText(mail.getContent());
        // 发送邮件

        javaMailSender.send(message);
    }

    @Override
    public void sendAttachFileMail(Mail mail) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject(mail.getObject());
        helper.setTo(String.join(",", mail.getTo()));
        // 设置邮件抄送人，可以有多个抄送人
        helper.setCc(String.join(",", mail.getCopy()));
        // 设置邮件发送日期
        helper.setSentDate(new Date());
        helper.setText(mail.getContent());
        // 第一个参数是自定义的名称，后缀需要加上，第二个参数是文件的位置
        helper.addAttachment(mail.getFile().getName(), mail.getFile());
        javaMailSender.send(mimeMessage);

    }

}
